package com.example.demo4DiyLogin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo4DiyLogin.model.UserDetail;
import com.example.demo4DiyLogin.model.UserModel;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
    private final UserService userService;
    /**
     * 通过username获取用户返回一个UserDetails对象
     * 这个实例中自定义了一个UserDetail，实现了UserDetails接口，为了方便所以UserDetail很简单
     * @param username the username identifying the user whose data is required.
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetail loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<UserModel> userModelQueryWrapper = new QueryWrapper<>();
        userModelQueryWrapper.eq("username",username);
        UserModel user = userService.getOne(userModelQueryWrapper);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }

        UserDetail userDetail = new UserDetail();
        userDetail.setUsername(user.getUsername());
        userDetail.setPassword(user.getPassword());
        return userDetail;

    }
}
